import './StudentManagement.scss';
import { useState, useMemo, useEffect } from 'react';
import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Table,
  Drawer,
  Tree,
  Modal,
  Select,
  message,
} from 'antd';
import {
  SearchOutlined,
  DoubleRightOutlined,
  EditOutlined,
  PlusCircleOutlined,
  MinusCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import {
  getStudent,
  selClass,
  getGradeId,
  addStudent,
  delStudent,
  editStudent,
} from '../../../../apis/data/studentManagementAPI';

const { Search } = Input;
const x = 3;
const y = 2;
const z = 1;
const defaultData: DataNode[] = [];

const generateData = (
  _level: number,
  _preKey?: React.Key,
  _tns?: DataNode[]
) => {
  const preKey = _preKey || '0';
  const tns = _tns || defaultData;

  const children: React.Key[] = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

const dataList: { key: React.Key; title: string }[] = [];
const generateList = (data: DataNode[]) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const { key } = node;
    dataList.push({ key, title: key as string });
    if (node.children) {
      generateList(node.children);
    }
  }
};
generateList(defaultData);

const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};

const StudentManagement: React.FC = () => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, defaultData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const treeData = useMemo(() => {
    const loop = (data: DataNode[]): DataNode[] =>
      data.map((item) => {
        const strTitle = item.title as string;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(defaultData);
  }, [searchValue]);

  interface DataType {
    key: React.Key;
    s_id: number;
    s_name: string;
    s_tel: string;
    s_idCard: string;
    g_grade: string;
    c_class: string;
    s_status: number;
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '学号',
      dataIndex: 's_id',
    },
    {
      title: '学生姓名',
      dataIndex: 's_name',
    },
    {
      title: '手机号码',
      dataIndex: 's_tel',
    },
    {
      title: '身份证号',
      dataIndex: 's_idCard',
    },
    {
      title: '年级',
      dataIndex: 'g_grade',
    },
    {
      title: '班级',
      dataIndex: 'c_class',
    },
    {
      title: '状态',
      dataIndex: 's_status',
      render: (_, record) => <>{record.s_status === 0 ? '启用' : '停用'}</>,
    },
  ];

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows
      );
      setDelId(selectedRowKeys);
      setEditData(selectedRows);
    },
  };

  /* var and func */
  const [page, setPage] = useState(1);
  const [count, setCount] = useState(5);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState('');
  const [data, setData] = useState<DataType[]>([]);
  const [classData, setClassData] = useState([]);
  const [gradeData, setGradeData] = useState([]);
  const [delId, setDelId] = useState<React.Key[]>([]);
  const [editData, setEditData] = useState<DataType[]>([]);

  const [open, setOpen] = useState<boolean>(false);
  const [addOpen, setAddOpen] = useState<boolean>(false);
  const [editOpen, setEditOpen] = useState<boolean>(false);
  const [delOpen, setDelOpen] = useState(false);

  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  //render
  const getData = () => {
    getStudent({ page: page, count: count, search: search }).then(
      (res: any) => {
        if (res.error === 0) {
          setTotal(res.total);
          let _data = res.data.map((v: any) => {
            return { ...v, key: v.s_id };
          });
          setData(_data);
        } else {
          message.error('数据获取失败');
        }
      }
    );
  };
  //init
  useEffect(() => {
    getData();
  }, [page, count, total, search]);
  //pagination
  const onChangeFn = (page: number, pageSize: number) => {
    setPage(page);
    setCount(pageSize);
  };
  //search
  const onSearch = (value: { search: string }) => {
    setSearch(value.search);
  };
  //reset
  const onReset = () => {
    setSearch('');
    form.resetFields();
  };
  //gradeData
  const gradeSel = () => {
    getGradeId().then((res: any) => {
      if (res.error === 0) {
        let _data = res.data.map((v: any) => {
          return { value: v.g_id, label: v.g_grade };
        });
        setGradeData(_data);
      } else {
        message.error('数据获取失败');
      }
    });
  };
  //classId
  const classSel = (value: number) => {
    selClass({ gradeId: value }).then((res: any) => {
      if (res.error === 0) {
        let _data = res.data.map((v: any) => {
          return { value: v.c_id, label: v.c_class };
        });
        setClassData(_data);
      } else {
        message.error('数据获取失败');
      }
    });
  };
  //add
  const onAdd = (value: any) => {
    addStudent(value).then((res: any) => {
      if (res.error === 0) {
        message.success('添加成功');
        getData();
        setAddOpen(false);
      } else {
        message.error('添加失败');
      }
    });
  };
  //delete
  const onDel = () => {
    delStudent({ id: delId[0] }).then((res: any) => {
      if (res.error === 0) {
        message.success('删除成功');
        setDelOpen(false);
        getData();
      } else {
        message.error('删除失败');
      }
    });
  };
  //edit
  const showEditModal = () => {
    if (editData.length === 0) return;
    setEditOpen(true);
    let data = {
      id: editData[0].s_id,
      name: editData[0].s_name,
      tel: editData[0].s_tel,
      idCard: editData[0].s_idCard,
      grade: editData[0].g_grade,
      classId: editData[0].c_class,
      status: editData[0].s_status === 0 ? '启用' : '停用',
    };
    editForm.setFieldsValue(data);
  };
  const onEdit = (value: any) => {
    switch (value.status) {
      case '启用':
        value.status = 0;
        break;
      case '停用':
        value.status = 1;
        break;
      case 0:
        value.status = 0;
        break;
      case 1:
        value.status = 1;
        break;
    }
    editStudent({
      id: editData[0].key,
      name: value.name,
      tel: value.tel,
      idCard: value.idCard,
      status: value.status,
    }).then((res: any) => {
      if (res.error === 0) {
        message.success('编辑成功');
        getData();
        setEditOpen(false);
      } else {
        message.error('编辑失败');
      }
    });
  };
  //advanced search
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  const onFinish = () => {};
  //upload
  const onUpload = () => {};
  return (
    <div className="container">
      <div className="student">
        <Breadcrumb separator=">">
          <Breadcrumb.Item>
            <Button type="link" style={{ color: '#333' }}>
              数据管理
            </Button>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Button type="link" style={{ color: '#333' }}>
              学生管理
            </Button>
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="content-box">
          <div className="left-box">
            <div className="left-title">
              <div style={{ marginLeft: '20px' }}>组织机构</div>
              <div>
                <EditOutlined style={{ marginRight: '20px' }} />
                <PlusCircleOutlined style={{ marginRight: '20px' }} />
                <MinusCircleOutlined style={{ marginRight: '20px' }} />
              </div>
            </div>
            <div className="left-content">
              <Search
                style={{ marginBottom: 30, marginTop: 32, width: 230 }}
                placeholder="请搜索"
                onChange={onChange}
              />
              <Tree
                style={{ width: 230 }}
                showLine={true}
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                treeData={treeData}
              />
            </div>
          </div>
          <div className="right-box">
            <div className="header-box">
              <div className="operation-box">
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={() => {
                    setAddOpen(true);
                  }}
                >
                  新增
                </Button>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={showEditModal}
                >
                  修改
                </Button>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={() => {
                    setDelOpen(true);
                  }}
                >
                  删除
                </Button>
              </div>
              <div className="search-box">
                <Form
                  form={form}
                  name="control-hooks"
                  layout="inline"
                  onFinish={onSearch}
                >
                  <Form.Item name="search">
                    <Input placeholder="请输入关键字搜索" />
                  </Form.Item>

                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      htmlType="submit"
                    >
                      <SearchOutlined />
                    </Button>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      onClick={onReset}
                    >
                      重置
                    </Button>
                  </Form.Item>
                </Form>
                <Button type="link" onClick={showDrawer}>
                  高级筛选
                  <DoubleRightOutlined
                    rotate={90}
                    style={{ color: '#d4d2d2' }}
                  />
                </Button>
              </div>
            </div>
            <div className="drawer">
              <Drawer
                title="高级筛选"
                style={{
                  marginLeft: '300px',
                  marginTop: '200px',
                  width: '82%',
                }}
                placement="top"
                height={200}
                closable={true}
                onClose={onClose}
                open={open}
                getContainer={false}
              >
                <Form
                  layout="inline"
                  name="highSearch"
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  autoComplete="off"
                >
                  <Form.Item label="姓名" name="name">
                    <Input placeholder="请输入姓名" />
                  </Form.Item>

                  <Form.Item label="身份证号" name="idCard">
                    <Input placeholder="请输入身份证号" />
                  </Form.Item>

                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      htmlType="submit"
                    >
                      查询
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      onClick={onReset}
                    >
                      重置
                    </Button>
                  </Form.Item>
                </Form>
              </Drawer>
            </div>
            <Table
              bordered={true}
              rowSelection={{
                type: 'radio',
                ...rowSelection,
              }}
              columns={columns}
              dataSource={data}
              pagination={{
                defaultPageSize: 5,
                defaultCurrent: 1,
                total: total,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: [5, 10, 15, 20],
                position: ['bottomLeft'],
                onChange: onChangeFn,
              }}
            />
          </div>
        </div>
      </div>
      {/* 新增 */}
      <Modal
        title="学生管理-新增"
        centered
        open={addOpen}
        onCancel={() => setAddOpen(false)}
        width={1280}
        destroyOnClose={true}
        footer={null}
      >
        <Form
          name="addData"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
          autoComplete="off"
          onFinish={onAdd}
        >
          <Form.Item label="学号" name="id">
            <Input placeholder="请输入学号" disabled />
          </Form.Item>
          <Form.Item label="学生姓名" name="name">
            <Input placeholder="请输入学生姓名" />
          </Form.Item>
          <Form.Item label="手机号码" name="tel">
            <Input placeholder="请输入手机号码" />
          </Form.Item>
          <Form.Item label="身份证号码" name="idCard">
            <Input placeholder="请输入身份证号" />
          </Form.Item>
          <Form.Item label="年级" name="grade">
            <Select
              options={gradeData}
              onFocus={gradeSel}
              onSelect={classSel}
              placeholder="请选择年级"
            />
          </Form.Item>
          <Form.Item label="班级" name="classId">
            <Select options={classData} placeholder="请选择班级" />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              options={[
                {
                  value: '0',
                  label: '启用',
                },
                {
                  value: '1',
                  label: '停用',
                },
              ]}
              placeholder="请选择状态"
            />
          </Form.Item>
          <Form.Item label=" ">
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              htmlType="submit"
            >
              新增
            </Button>
            <Button
              type="primary"
              style={{ background: '#69657e', marginLeft: '200px' }}
              onClick={() => {
                setAddOpen(false);
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑 */}
      <Modal
        title="学生管理-编辑"
        centered
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        width={1280}
        destroyOnClose={true}
        footer={null}
        forceRender
      >
        <Form
          form={editForm}
          name="editData"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
          autoComplete="off"
          onFinish={onEdit}
        >
          <Form.Item label="学号" name="id">
            <Input placeholder="请输入学号" disabled />
          </Form.Item>
          <Form.Item label="学生姓名" name="name">
            <Input placeholder="请输入学生姓名" />
          </Form.Item>
          <Form.Item label="手机号码" name="tel">
            <Input placeholder="请输入手机号码" />
          </Form.Item>
          <Form.Item label="身份证号码" name="idCard">
            <Input placeholder="请输入身份证号" />
          </Form.Item>
          <Form.Item label="年级" name="grade">
            <Select
              options={gradeData}
              onFocus={gradeSel}
              onSelect={classSel}
              placeholder="请选择年级"
              disabled
            />
          </Form.Item>
          <Form.Item label="班级" name="classId">
            <Select options={classData} placeholder="请选择班级" disabled />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              options={[
                {
                  value: '0',
                  label: '启用',
                },
                {
                  value: '1',
                  label: '停用',
                },
              ]}
              placeholder="请选择状态"
            />
          </Form.Item>
          <Form.Item label=" ">
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              htmlType="submit"
            >
              编辑
            </Button>
            <Button
              type="primary"
              style={{ background: '#69657e', marginLeft: '200px' }}
              onClick={() => {
                setEditOpen(false);
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 删除 */}
      <Modal
        title="提示"
        open={delOpen}
        onOk={onDel}
        onCancel={() => {
          setDelOpen(false);
        }}
      >
        <p>确定要删除选中学生吗？</p>
      </Modal>
    </div>
  );
};

export default StudentManagement;
